package com.iwomy.envpro.platform.listener;


import cn.hutool.core.util.ObjectUtil;
import com.iwomy.envpro.platform.constant.RedisConstants;
import com.iwomy.envpro.platform.entity.AirMonitorEquipmentEntity;
import com.iwomy.envpro.platform.service.AirMonitorEquipmentService;
import com.iwomy.envpro.platform.service.AirRealTimeDataService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
	private AirMonitorEquipmentService airMonitorEquipmentService;


	public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
		super(listenerContainer);
	}


	/**
	 * 使用该方法监听，当我们key过期是自动调用该方法
	 *
	 * @param message
	 * @param pattern
	 */
	@Override
	public void onMessage(Message message, byte[] pattern) {
		//就是过期的key
		String key = message.toString();
		if (key.contains(RedisConstants.ENVPRO_DEVICS_KEY)) {
			//更新设备状态为离线

			String mn = key.replace(RedisConstants.ENVPRO_DEVICS_KEY, "");
			log.info("{}",mn);
			AirMonitorEquipmentEntity airMonitorEquipmentEntity = airMonitorEquipmentService.selectOneByEquipmentId(mn);
			if (ObjectUtil.isNull(airMonitorEquipmentEntity)) return;
			airMonitorEquipmentEntity.setStatus(1);
			airMonitorEquipmentService.updateById(airMonitorEquipmentEntity);
			return;
		}

	}
}
